package com.example.BluetoothTest;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
//import javax.microedition.io.*;
import javax.bluetooth.*;

import java.io.*;
//import javax.microedition.lcdui.Image;
//import java.util.Vector;
//import java.util.Timer;

//import java.util.logging.Logger;


public class BluetoothTestMidlet extends MIDlet 
   implements CommandListener {
    //List main_list,dev_list;
    private Form form;
    private StringItem StrItem;
    Command exit,ok,SearchCommand,RefreshCommand;
    private Image image;
    //public TextField txtField;
    public Gauge gauge;
    //TextBox cmd;
    Display display;
    //private static java.util.Vector devices,services;
    //private Timer Refreshtime = null;
    private BtInterfaceDisplay BtInterface;
    LocalDevice local;
    DiscoveryAgent agent;
    DataOutputStream dout;
    int currentDevice = 0;       //used as an indicator to the device queried for 
                                 //the echo server
    //private static Object lock=new Object();
    
public void startApp() {
    //main_list = new List("Search Devices",Choice.IMPLICIT);   //the main menu
    //dev_list  = new List("Select Device",Choice.IMPLICIT); //the list of devices
    //cmd       = new TextBox("Text to echo","",120,TextField.ANY);
	
	StrItem = new StringItem("", "\nBluetooth Search App");
    form = new Form(null, new Item[] {StrItem});
    exit      = new Command("Exit",Command.EXIT,2);
    SearchCommand      = new Command("Start",Command.ITEM,1);
    //RefreshCommand      = new Command("Set Refresh time",Command.ITEM,1);
    //ok        = new Command("Send",Command.OK,1);
    form.addCommand(exit);
    form.addCommand(SearchCommand);
    //form.addCommand(RefreshCommand);
    form.setTitle("Bluetooth");
    form.setCommandListener(this);
    display   = Display.getDisplay(this);
    display.setCurrent(form);
	try{
		image = Image.createImage("/btsimple.jpg");
	}catch(Exception e){
	}
    if(image != null)
    {
    	image = scale(image,15,20);
    	//image =createAlphaImage(image,0xffffffff); 
    	form.append(image);
    }
    form.append(new Gauge("\n", false, Gauge.INDEFINITE,
            Gauge.CONTINUOUS_RUNNING));
    gauge = new Gauge("\n\nRefresh interval(min)", true, 10, 0);
    form.append(gauge);
    //main_list.addCommand(exit);
    //main_list.addCommand(SearchCommand);
    //main_list.addCommand(RefreshCommand);
    //main_list.setCommandListener(this);
    //dev_list.addCommand(exit);
    //dev_list.setCommandListener(this);
    //cmd.addCommand(ok);
    //cmd.setCommandListener(this);
    //main_list.append("Bluetooth Searching Program",null);
    //display.setCurrent(main_list);
        
    }
public void commandAction(Command com, Displayable dis) {
    if (com == exit){                                              //exit triggered from the main form
        destroyApp(true);
        notifyDestroyed();
    }
    if(com == SearchCommand)
    {
    	BtInterface = new BtInterfaceDisplay(this);
    	if(BtInterface == null)
    	{
    		do_alert("BTDiscover create failed", 400);
    	}	
    }
   /* if(com == RefreshCommand)
    {
    	txtField = new TextField("Set Refresh time", "", 15, TextField.NUMERIC);
    	form.append(txtField);
    }*/
    if (com == List.SELECT_COMMAND){
        /*if (dis == main_list){                                     //select triggered from the main from
            if (main_list.getSelectedIndex() >= 0){                //find devices
            	//Refreshtime = new Timer();
            	//Refreshtime.schedule(FindDevices, 0, 2000);
                //FindDevices();
                //do_alert("Searching for devices...", Alert.FOREVER);
            }
        }*/
        /*if (dis == dev_list){                                      //select triggered from the device list
        	 StreamConnection conn = null;
          ServiceRecord service = (ServiceRecord)
                           services.elementAt(dev_list.getSelectedIndex());
           String url = service.getConnectionURL(
                                   ServiceRecord.NOAUTHENTICATE_NOENCRYPT,
                                  false);
            try {
                conn = (StreamConnection) Connector.open(url);       //establish the connection
                dout = new DataOutputStream(conn.openOutputStream());//Get the output stream
                display.setCurrent(cmd);                             //Show the textbox
            } catch (Exception e) {this.do_alert("Error Connecting" , 4000);}
        }*/
     }
    /*if(com == ok){                                                  //the user is sending a command
        try{
            dout.writeChars(cmd.getString() + "\n");
            dout.flush();
            cmd.setString("");
        } catch (Exception e) {this.do_alert("Error sending data" , 4000);} 
    }*/
}

public void do_alert(String msg,int time_out){
    if (display.getCurrent() instanceof Alert ){
        ((Alert)display.getCurrent()).setString(msg);
        ((Alert)display.getCurrent()).setTimeout(time_out);
    }else{
        Alert alert = new Alert("Bluetooth");
        alert.setString(msg);
        alert.setTimeout(time_out);
        display.setCurrent(alert);
    }
}

public static final Image scale (Image srcImage, int newW, int newH) {
    int srcW = srcImage.getWidth();
    int srcH = srcImage.getHeight();
    //Horizontal direction 
    Image tmp = Image.createImage(newW, srcH);
    Graphics g = tmp.getGraphics();
    //transparent image
	g.setColor(0xffffff);  
    g.fillRect(0, 0, newW, srcH); 


    for (int x = 0; x < newW; x++) {
        g.setClip(x, 0, 1, srcH);
        //by scale
        g.drawImage(srcImage,x-x*srcW/newW,0,Graphics.LEFT | Graphics.TOP);

    }

    //Vertical direction
    Image dst = Image.createImage(newW, newH);
    g = dst.getGraphics();


    for (int y = 0; y < newH; y++) {
        g.setClip(0, y, newW, 1);
        //by scale
        g.drawImage(tmp,0,y-y*srcH/newH,Graphics.LEFT | Graphics.TOP);
    }

    return dst;        
} 

private static Image createAlphaImage(Image img, int alphaColor) {  
	  int w = img.getWidth();  
	  int h = img.getHeight();  
	  int[] imgData = new int[w * h];  
	  int a=254;  
	  img.getRGB(imgData, 0, w , 0, 0, w, h);  
	  for (int i = 0; i < imgData.length; i++) {  
	   if ((imgData[i] & alphaColor) == alphaColor) {  
	    imgData[i] = (a<<24 )| (imgData[i] & alphaColor);  
	   }  
	  }  
	  Image immutableImg = Image.createRGBImage(imgData, w, h, true);  
	  return immutableImg;  
	 }  

/** Shows main menu of MIDlet on the screen. */
void show() {
    Display.getDisplay(this).setCurrent(form);
}

public void pauseApp() {}

public void destroyApp(boolean unconditional) {
	if(BtInterface != null)
	{
		BtInterface.destroy();
	}
}

}